# -*- coding:utf-8 -*-
# @FileName :views_api.py
# @user chunxiangjie
# @Time :2022/1/20 19:07
import requests
from django.shortcuts import render
from api_App.models import *
import time
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib import auth
import json
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
import logging
from api_App.view_send_api import Send_Api
import re

logger = logging.getLogger('django')


# Create your views here.
# def use(request):
#     res={}
#     res['name']=use.__name__
#     return render(request,'login.html')
def home(request):
    return render(request, 'login.html')


def DB_notice_1(request, message1='', error=''):
    """

    :param request:
    :type error: object
    """
    res = {}
    res['DB_notice'] = list(DB_notice.objects.all().values('content'))
    res['message'] = message1
    res['error'] = error
    return render(request, 'login.html', res)


# 登录
def DB_denglu(request):
    time.sleep(0.1)
    # 获取前段用户名和密码
    username = request.POST.get('username', None)
    password = request.POST.get('password', None)
    # 和数据库校验
    user = auth.authenticate(request=None, username=username, password=password)
    if user is None:  # 用户不存在
        return DB_notice_1(request, f'{username}用户不存在')
    # 用户存在
    else:
        auth.login(request, user)
        request.session['user'] = username
        # 跳转到首页
        return HttpResponseRedirect('/home/')


# 退出
def login_out(request):
    auth.logout(request)
    return HttpResponseRedirect('/login/')


# 注册
def DB_zhuce(request):
    time.sleep(0.1)
    # 获取前段用户名和密码
    username = request.GET['username']
    email = request.GET['email']
    password = request.GET['password']
    # 成功
    try:
        while (email.find("@") == -1 or not email.endswith('.com')):
            return DB_notice_1('request', '', f'邮箱{email}输入的有误')
        else:
            user = User.objects.create_user(username=username, email=email, password=password)
            auth.login(request, user)
            request.session['user'] = username
            # 跳转到首页
            return HttpResponseRedirect('/home/', )
    except:  # 用户已存在
        return DB_notice_1(request, f'用户名{username}已存在, 或者{email}邮箱格式有误')


# 看板数据
def DB_GET_DATE(request):
    # 获取id
    # user_id=request.user.id
    notice_datas = {}
    notice_datas['notice_datas'] = list(DB_notice.objects.all().values('content'))[::-1]
    for i in notice_datas['notice_datas']:
        i['content'] = i['content'][:2] + '.....' if len(i['content']) > 10 else i['content']
    # 根据id拿名字后续在写
    # for i in notice_datas['notice_datas']:
    #     from_user_name = get_object_or_404(User, pk=i[" from_user_id"]).username
    #     i["from_user_name"]=from_user_name
    notice_datas['overview'] = {'project_count': len(DB_project_list.objects.filter(deleted=False)),
                                'api_count': len(DB_case_set.objects.all()), }

    notice_datas['Watchs'] = {'api_paas': len(DB_case_set.objects.filter()), 'cases_pass': 66, 'api_loss': 50}

    notice_datas['contribution'] = {'user_pro_ject_ab': 11,
                                    'use_pro_cases_zb': 22,
                                    'user_api__zb': 99,
                                    'monitor': 55}
    return HttpResponse(json.dumps(notice_datas), content_type='application/json')


# 顶部数据
def get_DB_GET_DATE(request):
    real_time_dates = {'Api_shopp_count': len(DB_Api_list.objects.all()),
                       'UnReadNews_case_count': 1,
                       'user_run_count': 100,
                       'Watchs_api_count': len(DB_monitor.objects.all())}
    return HttpResponse(json.dumps(real_time_dates), content_type='application/json')
    # 进入vue首页


# 进入vue首页
@login_required()
def index_(request):
    return render(request, 'index.html')


# 获取数据
def get_DATE(request):
    # 搜索
    input = request.GET.get('input', None)
    if input:
        project_list_data = list((DB_project_list.objects.filter(name__contains=input) | DB_project_list.objects.filter(
            des__contains=input) | DB_project_list.objects.filter(name__contains=input)).values())[
                            ::-1]  # select * from 表 where name like %keys% or des like %keys% ;
    else:
        project_list_data = list(DB_project_list.objects.filter(deleted=False).values())[::-1]
    # 增加字段 creater_name
    for i in project_list_data:
        try:
            creater_name = get_object_or_404(User, pk=i['creater']).username
        except:
            creater_name = '无人认领'
        i["creater"] = creater_name
    return HttpResponse(json.dumps(project_list_data), content_type='application/json')


# 新增
def add_project(request):
    uid = request.user.id if request.user.id else 0
    creat_ime = time.strftime('%Y-%m-%d %H:%M')
    DB_project_list.objects.create(creater=uid, create_time=creat_ime, )
    return get_DATE(request)


# 删除
def delete_pro_ject(request):
    id = request.GET['pro_ject_id']
    print(request.GET)
    DB_project_list.objects.filter(id=id).update(deleted=True)
    # DB_case_set.objects.filter(project_id=id).update(deleted=True)
    return get_DATE(request)


# 獲取單個項目详情
def get_pro_ject_all(request):
    id = request.GET['id']
    form = list(DB_project_list.objects.filter(id=id).values())[0]
    # form['power'] = eval(form['power'])
    return HttpResponse(json.dumps(form), content_type='application/json')


# 保存并生效
def save_project(request):
    form = json.loads(request.body.decode('utf-8'))
    DB_project_list.objects.filter(id=form['id']).update(**form)
    return HttpResponse('', content_type='application/json')


# ------------------------环境管管理 -------------------------------------------
# 获取环境列表
def get_envlist(request):
    env_list_data = DB_env_list.objects.all().values()[::1]
    return HttpResponse(json.dumps(env_list_data), content_type='application/json')


# 新增环境
def Add_env(request):
    form = json.loads(request.body.decode('utf-8'))
    DB_env_list.objects.create(**form)
    return get_envlist(request)


# 删除环境
def delete_ev(request):
    en_id = request.GET['en_id']
    DB_env_list.objects.filter(id=en_id).delete()
    return get_envlist(request)


# ------------------个人信息=-------------
def get_Userdaa(request):
    form_data = {
        'user': request.user.username,
        'password': '********',
        'title': request.user.first_name,
        'USER_id': request.user.id
    }
    try:
        form_data['title'] = request.user.first_name
    except:
        form_data['title'] = '无'
    return HttpResponse(json.dumps(form_data), content_type='application/json')


def sava_user(request):
    form = json.loads(request.body.decode('utf-8'))
    user = User.objects.get(id=request.user.id)
    user.username = form['user']
    user.first_name = form['title']
    if form['password'] != '********':
        user.set_password(form['password'])
        auth.logout(request)
    user.save()
    return HttpResponse('')


# 上传用户头像
def uploader_user_avater(request):
    MyFileName = request.FILES.get('uploader_name', None)
    name = request.user.username
    Filename = 'User_img_' + str(name) + '.jpg'
    fp = open('api_APP/static/User_img/' + Filename, 'wb+')
    for i in MyFileName.chunks():
        fp.write(i)
    fp.close()
    return HttpResponse('')


# ----------------------------- 接口商店----------------------------------------
# 获取接口列表
def get_api_shop_list(request):
    api_shop_list = list(DB_Api_list.objects.all().values())[::-1]
    return HttpResponse(json.dumps(api_shop_list), content_type='application/json')


# 保存接口
def save_api_shop(request):
    form = json.loads(request.body.decode('utf-8'))
    print(form)
    try:  # 说明编辑更新
        DB_Api_list.objects.filter(id=form['id']).update(**form)
    except:  # 新增
        DB_Api_list.objects.create(**form)
    return get_api_shop_list(request)


# 删除功能
def delete_api_shop(request):
    api_id = request.GET['api_id']
    DB_Api_list.objects.filter(id=api_id).delete()
    return get_api_shop_list(request)


# -------发送消息------
# 获取消息接收者用户列表
def get_to_user_list(request):
    res = {}
    to_user_list = list(User.objects.all().values('username', 'id', 'first_name'))
    for i in range(len(to_user_list)):
        to_user_list[i]['value'] = to_user_list[i]['username']
    res['to_user_list'] = to_user_list
    news = list(DB_notice.objects.filter(to_user_id=request.user.id).values())[::-1]
    for i in news:
        from_user_name = get_object_or_404(User, pk=i["from_user_id"]).username
        i["from_user_name"] = from_user_name
    res['news'] = news

    return HttpResponse(json.dumps(res), content_type='application/json')


# ----发送消息---
def send_news(resquest):
    data = json.loads(resquest.body.decode('utf-8'))
    print(data)
    to_user_id = data['to_user_id']
    content = data['notic']
    from_user_id = resquest.user.id
    date = str(time.strftime('%Y-%m-%d %H:%M:%S'))
    DB_notice.objects.create(to_user_id=to_user_id, content=content, from_user_id=from_user_id, date=date)
    return HttpResponse(get_to_user_list)


# 平台日志
def look_logs(request):
    res = {
        "logs": '',
        "error_count": 0,
        "error_lines": [],
        "warning_count": 0,
        "warning_lines": [],
    }
    with open('cxjinfo.txt', 'r') as fp:
        l = fp.readlines()[-1000:][::-1]
    # 加行号，统计错误行、错误数。警告行，警告数。
    for i in range(len(l)):
        if '[ERROR]' in l[i]:
            res['error_count'] += 1
            res['error_lines'].append(i + 1)
            res['logs'] += str(i + 1) + ' ' + '【错误行】：' + l[i]
        elif '[WARNING]' in l[i]:
            res['warning_count'] += 1
            res['warning_lines'].append(i + 1)
            res['logs'] += str(i + 1) + ' ' + '【警告行】：' + l[i]
        else:
            res['logs'] += str(i + 1) + ' ' + l[i]
    return HttpResponse(json.dumps(res), content_type='application/json')


# ------------权限管理---------------
# 获取
def get_power_list(request):
    # res = {}
    #
    # power_list_data = list(DB_power.objects.all().values())
    # for i in power_list_data:
    #     i['users'] = eval(i['users'])
    # res['power_list_data'] = power_list_data
    #
    # all_users = list(User.objects.all().values( 'username'))
    # res['all_users'] = all_users
    res = {}
    power_list_data = list(DB_power.objects.all().values())[::1]
    res['power_list_data'] = power_list_data
    user = list(User.objects.all().values('username'))
    res['all_users'] = user
    all_paths = ''
    with open('api_App/views.py', 'r', encoding='utf-8') as fp:
        L = fp.readlines()
        for i in L:
            if 'def' in i:
                if '(request' in i:
                    all_paths += i
    res['all_paths'] = all_paths
    return HttpResponse(json.dumps(res), content_type='application/json')


# 新增
def add_power(request):
    if request.user.id != 1:
        logging.warning('%s 试图进入权限管理模块，已被固定最高级权限拦截！' % request.user.username)
        return HttpResponse(json.dumps({}), content_type='application/json')
    DB_power.objects.create()
    return get_power_list(request)


# 删除
def delete_power(request):
    power_id = request.GET['id']
    DB_power.objects.filter(id=power_id).delete()
    return get_power_list(request)


# 保存
def save_power(request):
    if request.user.id != 1:
        logging.warning('%s 试图进入权限管理模块，已被固定最高级权限拦截！' % request.user.username)
        return HttpResponse(json.dumps({}), content_type='application/json')
    save_data = json.loads(request.body.decode('utf-8'))
    try:
        DB_power.objects.filter(id=save_data['id']).update(**save_data)
    except:
        DB_power.objects.create(**save_data)
    return get_power_list(request)


# 自定义特权判定函数
def diy_power(request, path):
    power = DB_power.objects.filter(power_path__contains=path)
    if power:  # 中了权限监管
        user_ids = [i.split('-')[0] for i in eval(power[0].users)]
        if str(request.user.id) in user_ids:
            # 有权限
            r = locals()
            exec('r = %s(request)' % path)
            return r['r']
        else:  # 没权限
            return HttpResponse('没权限')
    else:  # 没中
        return default_power(request, path)


# 自然默认权限判定函数
def default_power(request, path):
    if path == 'delete_project':
        project_id = request.GET['project_id']
        if request.user.id != DB_project_list.objects.filter(id=project_id)[0].creater:
            return HttpResponse('没权限')
    # if path =='':
    #     ...
    #
    # if path =='':
    #     ...
    #
    # if path =='':
    #     ...
    #
    # if path =='':
    #     ...
    if path in ['favicon.ico']:
        return HttpResponse('')
    # 有权限
    r = locals()
    exec('r = %s(request)' % path)
    return r['r']


# 下载接口到项目
def download_api(request):
    # args = DB_case_set.objects.all()
    # args.aggregate(Max('pro_ject_id'))
    # print(args.aggregate(Max('pro_ject_id')))
    project_id = request.GET['pro_ject_id']
    api_id = request.GET['api_id']
    api = list(DB_Api_list.objects.filter(id=int(api_id)).values())[0]
    api['project_id'] = project_id
    DB_case_set.objects.create(**api)
    return HttpResponse('')


# 在线监控
def get_monitor_list(request):
    get_monitor = list(DB_monitor.objects.all().values())[::1]
    return HttpResponse(json.dumps(get_monitor), content_type='application/json')

def save_monitor(request):
    data = json.loads(request.body.decode('utf-8'))
    monitor = DB_monitor.objects.filter(id=int(data['id']))
    monitor.update(**data)
    monitor.update(status=False)
    return get_monitor_list(request)

def add_monitor(request):
    DB_monitor.objects.create()
    return get_monitor_list(request)


def delete_monitor(request):
    monitor_id = request.GET['id']
    DB_monitor.objects.filter(id=int(monitor_id)).delete()
    return get_monitor_list(request)
# 更改触发时机
def change_monitor_status(request):
    id = request.GET['id']
    monitor = DB_monitor.objects.filter(id=int(id))[0]
    if monitor.status == True:# 我要关上
        monitor.status = False
    else: #我要打开
        monitor.status = True
        set_monitor_next(monitor,'human')
    # 必须保存
    monitor.save()
    return get_monitor_list(request)
# 下次执行时机
def set_monitor_next(monitor,which):
    if monitor.method == '间隔时间':
        if which == 'human':
            monitor.step = time.time() + int(monitor.value)*60
            return
        else: # 巡逻线程调用
            monitor.step = float(monitor.step) + float(monitor.value)*60
            print(type(float(monitor.step)))
            print(monitor.step)
    elif monitor.method == '每日定时':
        h = int(monitor.value.split(':')[0])
        m = int(monitor.value.split(':')[1])
        hm = h*3600 + m*60
        #当前0点时间
        today_s = int(time.time()) - int(time.time()-time.timezone)%86400 + hm
        if which == 'human':
            if today_s <= time.time() : #今天来不及了
                monitor.step = today_s + 86400
            else:
                monitor.step = today_s
        else: # 巡逻线程
            monitor.step = monitor.step + 86400
    elif monitor.method == 'jenkins语法':
        ...
def change_monitor_status(request):
    id = request.GET['id']
    monitor = DB_monitor.objects.filter(id=int(id))[0]
    if monitor.status == True: #说明要关闭
        monitor.status = False
    else:#说明要打开
        monitor.status = True
        set_monitor_next(monitor,'human')
    monitor.save()
    return get_monitor_list(request)

# 接口文档导入api
def import_api_ad(request):
    project_id = request.GET['project_id']
    form = json.loads(request.body.decode('utf-8'))
    form['project_id'] = project_id
    DB_Api_list.objects.create(**form)
    return HttpResponse('')

# 接口文档解析
def jx_apiDoc(request):
    ad_url = request.GET['ad_url']
    response = requests.get(ad_url)
    # 发送请求，读取页面内容
    form = {}
    # 正则解析
    form['url'] = re.findall('url:(.*?)\n',response.text)

    return HttpResponse(json.dumps(form),content_type='application/json')

# postman 文件上传
def upload_postman_file(request):
    myFile = request.FILES.get('postman_file', None)
    file_name = str(myFile)
    fp = open('Api_app/static/postmanFileFolder/' + file_name, 'wb+')
    for i in myFile.chunks():
        fp.write(i)
    fp.close()
    return HttpResponse('')

# postman 文件解析
def jx_postman(request):
    project_id = request.GET['project_id']
    file_name = request.GET['file_name']
    with open('Api_app/static/postmanFileFolder/'+file_name,'r') as fp:
        lines = fp.read()
    lines = json.loads(lines)
    item = lines['item']

    for i in item:
        form = {
            'project_id':project_id,
            'label':i['name'],
            'type':'api',
            'children':'[]',
            'des':'',
            'host': i['request']['url']['protocol']+'://'+'.'.join(i['request']['url']['host']),
            'path': '/'+'/'.join(i['request']['url']['path']),
            'method':i['request']['method'],
            'params': str( i['request']['url'].get('query',[]) ),
            'headers':str(  i['request']['header']   ),
            'payload_method':i['request'].get('body',{}).get('mode',''),
            'payload_fd':'[]',
            'payload_xwfu':'[]',
            'payload_raw_method':'',
            'payload_raw':'',
            'payload_binary':'',
            'payload_GQL_q': '',
            'payload_GQL_g': '',
        }
        if i['request']['url'].get('port',None):
            form['host'] += ':'+i['request']['url']['port']
        form['payload_method'] = form['payload_method'].replace('urlencoded','x-www-form-urlencoded').\
            replace('graphql','GraphQL').replace('formdata','form-data')
        if form['payload_method'] == 'form-data':
            form['payload_fd'] = str(i['request']['body']['formdata'])
        if form['payload_method'] == 'x-www-form-urlencoded':
            form['payload_xwfu'] = str(i['request']['body']['urlencoded'])
        if form['payload_method'] == 'GraphQL':
            form['payload_GQL_q'] = i['request']['body']['graphql']['query']
            form['payload_GQL_g'] = i['request']['body']['graphql']['variables']
        if form['payload_method'] == 'raw':
            form['payload_raw'] = i['request']['body']['raw']
            if i['request']['body'].get('options',None):
                form['payload_raw_method'] = i['request']['body']['options']['raw']['language']
                form['payload_raw_method'] = form['payload_raw_method'].replace('javascript','JavaScript').replace('json','JSON').replace('html','HTML').replace('xml','XML')
            else:
                form['payload_raw_method'] = 'Text'
        DB_Api_list.objects.create(**form)
        form = {}

    return HttpResponse('')


